package movee.utils.network;

import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.config.Registry;
import org.apache.hc.core5.http.config.RegistryBuilder;

import java.util.concurrent.TimeUnit;

/**
 *
 *
 * @author movee
 */
@Slf4j
public final class ApacheHttpClientUtils {

    private ApacheHttpClientUtils() { }

    public static HttpClient buildHttpClient(long connectTimeoutMs,
                                             long connectionRequestTimeoutMs,
                                             long responseTimeoutMs,
                                             int maxConnectionSize,
                                             int maxConnectionPerRoute) {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        // 设置整个连接池最大连接数 根据自己的场景决定
        connectionManager.setMaxTotal(maxConnectionSize);
        // 路由是对maxTotal的细分
        connectionManager.setDefaultMaxPerRoute(maxConnectionPerRoute);
        RequestConfig requestConfig = RequestConfig.custom()
                // 服务器返回数据(response)的时间，超过该时间抛出read timeout
                .setResponseTimeout(responseTimeoutMs, TimeUnit.MILLISECONDS)
                // 连接上服务器(握手成功)的时间，超出该时间抛出connect timeout
                .setConnectTimeout(connectTimeoutMs, TimeUnit.MILLISECONDS)
                // 从连接池中获取连接的超时时间，
                // 超过该时间未拿到可用连接，会抛出org.apache.http.conn.ConnectionPoolTimeoutException:
                // Timeout waiting for connection from pool
                .setConnectionRequestTimeout(connectionRequestTimeoutMs, TimeUnit.MILLISECONDS)
                .build();
        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .build();
    }

}
